package com.alien.admin.context.task.handle.impl;

import com.alien.admin.context.task.DeployStatusTimeline;
import com.alien.admin.context.task.handle.DeployJobHandler;
import com.alien.admin.context.task.TaskQueue;
import com.alien.admin.modules.deploy.domain.DeployRec;
import com.alien.admin.modules.deploy.repository.DeployRecRepository;
import com.alien.admin.modules.deploy.service.DeployService;
import com.alien.admin.utils.DeployConstant;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description:
 * @Author: zsy
 * @Date: 2021/10/28 11:22
 */
@Slf4j
@Data
@Component
public class K8sDeployJobHandler implements DeployJobHandler {
    @Autowired
    private DeployService deployService;
    @Autowired
    private DeployRecRepository deployRecRepository;
    @Autowired
    private TaskQueue taskQueue;
    @Autowired
    private DeployStatusTimeline deployStatusTimeline;

    @Override
    public void process(DeployRec deployRec) {
        Boolean hasDeployed = deployStatusTimeline.isAlive(deployRec.getId());
        // 防止一条记录被部署多次
        if(!hasDeployed) {
            // 进入部署
            DeployRec k8sDeployRec = deployService.deploy(deployRec.getId());
            if(!DeployConstant.DEPLOY_STATUS_FAILED.equals(k8sDeployRec.getDeployStatus())) {

                // 任务中途被取消检验
                if(taskQueue.isCancelTask(deployRec.getId())) {
                    return;
                }

                // 部署后，进入jenkins job状态监测
                k8sDeployRec.setStage(DeployConstant.DEPLOY_STAGE_HEALTH_CHECK);
                k8sDeployRec.setDeployStatus(DeployConstant.DEPLOY_STATUS_NONE);
                deployRecRepository.save(k8sDeployRec);

                // 设置健康监测时间
                deployStatusTimeline.putRecId(deployRec.getId(), 1000L);
                taskQueue.putTaskToQueue(deployRec.getId());
            }
        }
    }
}
